﻿using System;
using System.Collections.Generic;
using NHibernate;
using YunBox2.Contracts.Core;

namespace YunBox2.Server.Core
{
    public abstract class BizBase<T>
        where T : BizObject
    {
        protected readonly ISession Session;
        protected readonly User User;

        protected BizBase(ISession session, User user)
        {
            Session = session;
            User = user;
        }

      

        protected virtual Guid ModuleId
        {
            get
            {
                return Guid.Empty;
            }
        }

        protected virtual Permission GetPermission()
        {
            Permission permission = Session.QueryOver<Permission>().Where(x => x.OwnerID == User.Id && x.ModuleID == ModuleId).SingleOrDefault();
            if (permission == null)
            {
                permission = new Permission {Approve = false, Audit = false, Edit = false, Extensions = "<permission/>", Id = Guid.Empty, Invalid = false, ModuleID = ModuleId, OwnerID = User.Id ?? Guid.Empty, Print = false, Remove = false};
            }
            return permission;
        }

        public virtual IList<T> GetAllBizObjects()
        {
            return Session.QueryOver<T>().List();
        }

        public virtual T Get(Guid id)
        {
            return Session.Get<T>(id);
        }

        public virtual T Load(Guid id)
        {
            return Session.Load<T>(id);
        }

        public virtual T Save(T source)
        {
            source.LastModifiedTime = DateTime.Now;
            source.LastModifiedUser = User;
            Session.Save(source);
            Session.Flush();
            return source;
        }

        public virtual T Update(T source)
        {
            if (!source.Id.HasValue)
            {
                return null;
            }
            source.LastModifiedTime = DateTime.Now;
            source.LastModifiedUser = User;
            Session.Merge(source);
            Session.Flush();
            return Get(source.Id.Value);
        }

        public virtual bool Remove(Guid id)
        {
            T obj = Get(id);
            if (obj == null)
            {
                return false;
            }
            Session.Delete(id);
            Session.Flush();
            return true;
        }
    }
}